package netStudy;

import java.io.IOException;
import java.net.*;
import java.util.Scanner;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 34255
 * Date: 2024-11-13
 * Time: 16:33
 */
public class UdpEchoClient {
    private DatagramSocket UdpClient = null;
    private int ServePort;//服务端端口号
    private String ServeIP;//服务端IP地址

    public UdpEchoClient(int ServePort,String ServeIP) throws SocketException {
        //使用无参构造，为客户端绑定随机的端口号
        UdpClient = new DatagramSocket();
        this.ServeIP = ServeIP;
        this.ServePort = ServePort;
    }

    public void sendRequest() throws IOException {
        //客户端发送请求
        System.out.println("客户端连接成功");
        Scanner scanner  = new Scanner(System.in);
        while(true){

            //从控制台读取用户输入的内容.
            System.out.println("请输入要发送的内容:");
            if (!scanner.hasNext()) {
                break;
            }
            String request = scanner.next();

            //创建数据报存储请求内容
            //getByName()返回主机的IP地址，传String类型的IP地址来构造出一个主机的IP地址
            DatagramPacket packet = new DatagramPacket(request.getBytes(),0,request.getBytes().length,InetAddress.getByName(ServeIP),ServePort);

            //向服务端发送请求
            UdpClient.send(packet);

            //接收服务端返回的响应内容
            //创建数据报接收响应内容
            DatagramPacket packet1 = new DatagramPacket(new byte[1024],1024);
            //读取数据内容
            UdpClient.receive(packet1);

            //解析响应内容
            String response = new String(packet1.getData(),0,packet1.getLength());

            //打印响应内容
            System.out.println(request);
        }
    }

    public static void main(String[] args) throws IOException {
        //客户端
        UdpEchoClient client = new UdpEchoClient(9990,"127.0.0.1");
        client.sendRequest();
    }
}
